package cn.itcast.service.mobileImpl;

import cn.itcast.constant.RedisConstant;
import cn.itcast.dao.MemberDao;
import cn.itcast.mobile.MobileMemberService;
import cn.itcast.pojo.Member;
import cn.itcast.template.SmsTemplate;
import cn.itcast.utils.DateUtils;
import cn.itcast.utils.JwtUtils;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Demo class
 *
 * @author gyc
 * @date 2021/10/17
 */
@Service
public class MobileMemberServiceImpl implements MobileMemberService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberDao memberDao;

    @Override
    public boolean sendCode(String phone) {
        //1. 生成随机验证码
        //String code = RandomStringUtils.random(6);
        //2. 调用阿里云发送验证码
        //判断验证码是否还未失效
        if (redisTemplate.hasKey(RedisConstant.SENDTYPE_LOGIN +phone)) {
            throw new RuntimeException("验证码还未失效");
        }
        String code = "123456";
        //发送短信
        //smsTemplate.SendSms(phone,code);
        //3. 将验证码保存到redis
        redisTemplate.opsForValue().set(RedisConstant.SENDTYPE_LOGIN +phone,code, Duration.ofSeconds(30));
        return true;
    }

    @Override
    public Map loginVerification(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(RedisConstant.SENDTYPE_LOGIN + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new RuntimeException("验证码错误");
        }
        //3、删除redis中的验证码
        redisTemplate.delete(RedisConstant.SENDTYPE_LOGIN + phone);
        //4、通过手机号码查询用户
        Member member = memberDao.findByPhone(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        if(member == null) {
            member = new Member();
            member.setPhoneNumber(phone);
            member.setPassword(DigestUtils.md5Hex(code));
            member.setRegTime(DateUtils.getToday());
            Integer memberId = memberDao.save(member);
            member.setId(memberId);
            isNew = true;
        }
        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id",member.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        return retMap;
    }
}
